package com.ruix.app.widget.chatrow;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMVoiceMessageBody;
import com.hyphenate.easeui.widget.EaseImageView;
import com.hyphenate.easeui.widget.chatrow.EaseChatRowFile;
import com.ruix.app.R;
import com.ruix.app.manager.UserManager;
import com.ruix.app.model.ChatAuther;
import com.ruix.app.model.Classes;
import com.ruix.app.network.RXObserver;
import com.ruix.app.network.RequestFactory;
import com.ruix.app.util.RoleUtil;
import com.ruix.app.util.ViewUtil;
import com.ruix.app.util.VoiceRecorder;

import org.json.JSONObject;

import io.reactivex.disposables.Disposable;

/**
 * Created by hadexs on 2017/5/29.
 */

public class ChatRowVoice extends EaseChatRowFile {

    private ImageView voiceImageView;
    private TextView voiceLengthView;
    private ImageView readStatusView;
    private TextView autherNameView;
    private TextView autherTagView;
    private TextView likeStatus;
    private EaseImageView userAvatar;
    private int bubbleWidth;
    private int lenghtWidth;

    public ChatRowVoice(Context context, EMMessage message, int position, BaseAdapter adapter) {
        super(context, message, position, adapter);
        bubbleWidth = (int) context.getResources().getDimension(R.dimen.h_w_65);
//        lenghtWidth = (int) context.getResources().getDimension(R.dimen.h_w_2);
        lenghtWidth = (int) (ViewUtil.getWindowWidth(context) * 0.44 - bubbleWidth) / 60;
    }


    @Override
    protected void onInflateView() {
        inflater.inflate(message.direct() == EMMessage.Direct.RECEIVE ?
                com.hyphenate.easeui.R.layout.ease_row_received_voice : com.hyphenate.easeui.R.layout.ease_row_sent_voice, this);
    }

    @Override
    protected void onFindViewById() {
        voiceImageView = ((ImageView) findViewById(com.hyphenate.easeui.R.id.iv_voice));
        voiceLengthView = (TextView) findViewById(com.hyphenate.easeui.R.id.tv_length);
        readStatusView = (ImageView) findViewById(com.hyphenate.easeui.R.id.iv_unread_voice);
        autherNameView = (TextView) findViewById(com.hyphenate.easeui.R.id.tv_auther_name);
        autherTagView = (TextView) findViewById(com.hyphenate.easeui.R.id.tv_auther_tag);
        userAvatar = (EaseImageView) findViewById(com.hyphenate.easeui.R.id.iv_userhead);
        likeStatus = (TextView) findViewById(com.hyphenate.easeui.R.id.message_like);


    }

    @Override
    protected void onSetUpView() {
        handelUserInfo();
        EMVoiceMessageBody voiceBody = (EMVoiceMessageBody) message.getBody();
        int len = voiceBody.getLength();
        if(len>0){
            len = len > 60 ? 60: len;
            voiceLengthView.setText(len + "\"");
            voiceLengthView.setVisibility(View.VISIBLE);
            ViewGroup.LayoutParams params =  bubbleLayout.getLayoutParams();
            params.width = bubbleWidth + len * lenghtWidth;
            bubbleLayout.setLayoutParams(params);
        }else{
            voiceLengthView.setVisibility(View.INVISIBLE);
        }
        if (ChatRowVoicePlayClickListener.playMsgId != null
                && ChatRowVoicePlayClickListener.playMsgId.equals(message.getMsgId()) && ChatRowVoicePlayClickListener.isPlaying) {
            AnimationDrawable voiceAnimation;
            if (message.direct() == EMMessage.Direct.RECEIVE) {
                voiceImageView.setImageResource(com.hyphenate.easeui.R.anim.voice_from_icon);
            } else {
                voiceImageView.setImageResource(com.hyphenate.easeui.R.anim.voice_to_icon);
            }
            voiceAnimation = (AnimationDrawable) voiceImageView.getDrawable();
            voiceAnimation.start();
        } else {
            if (message.direct() == EMMessage.Direct.RECEIVE) {
                voiceImageView.setImageResource(com.hyphenate.easeui.R.drawable.ease_chatfrom_voice_playing);
            } else {
                voiceImageView.setImageResource(com.hyphenate.easeui.R.drawable.ease_chatto_voice_playing);
            }
        }

        likeStatus.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (itemClickListener != null){
                    itemClickListener.onLickClick(message);
                }
                didLikeClick();
            }
        });

        if (message.direct() == EMMessage.Direct.RECEIVE) {
            if (message.isListened()) {
                readStatusView.setVisibility(View.GONE);
            } else {
                readStatusView.setVisibility(View.VISIBLE);
            }
        } else {
            if (message.status() == EMMessage.Status.INPROGRESS){
                if (progressBar != null) {
                    progressBar.setVisibility(View.VISIBLE);
                }
                if (statusView != null) {
                    statusView.setVisibility(View.GONE);
                }
            } else if (message.status() == EMMessage.Status.FAIL){
                if (statusView != null) {
                    statusView.setVisibility(View.VISIBLE);
                }
                if (progressBar != null) {
                    progressBar.setVisibility(View.GONE);
                }
            } else if (message.status() == EMMessage.Status.SUCCESS){
                if (progressBar != null) {
                    progressBar.setVisibility(View.INVISIBLE);
                }
                if (statusView != null) {
                    statusView.setVisibility(View.INVISIBLE);
                }
            }
//            handleSendMessage();
        }

//            EMLog.d(TAG, "it is receive msg");
//            if (voiceBody.downloadStatus() == EMFileMessageBody.EMDownloadStatus.DOWNLOADING ||
//                    voiceBody.downloadStatus() == EMFileMessageBody.EMDownloadStatus.PENDING) {
//                progressBar.setVisibility(View.VISIBLE);
//                setMessageReceiveCallback();
//            } else {
//                progressBar.setVisibility(View.INVISIBLE);
//
//            }
//            return;
//        }

        // until here, handle sending voice message
//        progressBar.setVisibility(View.INVISIBLE);
//        handleSendMessage();
    }

    @Override
    protected void onUpdateView() {
        super.onUpdateView();
    }

    @Override
    protected void onBubbleClick() {
        if (VoiceRecorder.isRecording){
            return;
        }
        new ChatRowVoicePlayClickListener(message, voiceImageView, readStatusView, adapter, activity).onClick(bubbleLayout);
        setRead();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (ChatRowVoicePlayClickListener.currentPlayListener != null && ChatRowVoicePlayClickListener.isPlaying) {
            ChatRowVoicePlayClickListener.currentPlayListener.stopPlayVoice();
        }
    }


    private void handelUserInfo(){
        try {
            JSONObject authorObj =  message.getJSONObjectAttribute("author");
            if (authorObj != null) {
                String authID = authorObj.optString("id", "");
                ChatAuther chatAuther =  UserManager.sharedInstance().getChatAuther(authID);
                if (chatAuther == null){
                    chatAuther = new ChatAuther();
                    String authName = authorObj.optString("name", "");
                    String roleid = authorObj.optString("role", "");
                    String roleVale = authorRoleValue(roleid);
                    String authAvatar = authorObj.optString("avatar", "");

                    chatAuther.setAuthID(authID);
                    chatAuther.setRoleid(roleid);
                    chatAuther.setAuthName(authName);
                    chatAuther.setRoleVale(roleVale);
                    chatAuther.setAuthAvatar(authAvatar);
                    UserManager.sharedInstance().addChatAuther(chatAuther);
                }
                if (!TextUtils.isEmpty(chatAuther.getAuthName())) {
                    autherNameView.setText(chatAuther.getAuthName());
                }
                if (!TextUtils.isEmpty(chatAuther.getAuthAvatar())) {
                    userAvatar.loadHeaderView(chatAuther.getAuthAvatar());
                }
                if (!TextUtils.isEmpty(chatAuther.getRoleVale())) {
                    autherTagView.setText(chatAuther.getRoleVale());
                    autherTagView.setVisibility(VISIBLE);
                } else {
                    autherTagView.setVisibility(GONE);
                }

                if (RoleUtil.isLikedUnusable(chatAuther.getRoleid())){ //班主任的消息不能被点赞
                    likeStatus.setVisibility(GONE);
                } else {
                    likeStatus.setVisibility(VISIBLE);
                    //点赞的逻辑
                    boolean  hasLike =  message.getIntAttribute("has_like",0) == 1;
                    int  likeCnt =  message.getIntAttribute("like_cnt",0);
                    if (likeCnt > 0) {
                        likeStatus.setText(String.format("赞同%d", likeCnt));
                    } else {
                        likeStatus.setText("赞同");
                    }

                    if (hasLike && likeCnt > 0){
                        likeStatus.setBackgroundResource(com.hyphenate.easeui.R.drawable.ease_like_action_bg);
                    } else {
                        likeStatus.setBackgroundResource(com.hyphenate.easeui.R.drawable.ease_like_normal_bg);
                    }
                }
            }


        } catch (Exception e){

        }

    }


    private void didLikeClick(){
        boolean  hasLike =  message.getIntAttribute("has_like",0) == 1;
        int  likeCnt =  message.getIntAttribute("like_cnt",0);
        if (hasLike){
             likeCnt--;
            likeStatus.setBackgroundResource(com.hyphenate.easeui.R.drawable.ease_like_normal_bg);
             message.setAttribute("has_like",0);
        } else {
            likeCnt++;
            likeStatus.setBackgroundResource(com.hyphenate.easeui.R.drawable.ease_like_action_bg);
            message.setAttribute("has_like",1);
        }

        if (likeCnt > 0) {
            likeStatus.setText(String.format("赞同%d", likeCnt));
        } else {
            likeStatus.setText("赞同");
        }
        message.setAttribute("like_cnt",likeCnt);
    }

    private void setRead(){
        if (message.isListened()){
            return;
        }
        RequestFactory.setMessageReaded(message.getMsgId(), null, new RXObserver() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Object value) {
                //
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

    }


    public String authorRoleValue(String roleID){
        if (!TextUtils.isEmpty(roleID)) {
            if ("1".equals(roleID)){
                return "导师";
            } else if ("5".equals(roleID)){
                return "小助手";
            } else if ("6".equals(roleID)){
                return "嘉宾";
            } else if ("8".equals(roleID)){
                Classes currentClass =  UserManager.sharedInstance().getCurrentClass();
                if (currentClass != null &&  currentClass.isTeacherFriendCircle()){
                    return "导师";
                }
                return "班主任"; //
            } else if ("9".equals(roleID)){
                return "班委";
            } else if ("10".equals(roleID)){
                return "班长";
            }
        }
        return null;
    }

}
